#include <iostream>
#include <openssl/ec.h>
#include <openssl/obj_mac.h>
#include <openssl/ecdsa.h>
#include <openssl/pem.h>

int main() {
    // 初始化 OpenSSL 库
    OpenSSL_add_all_algorithms();

    // 创建 ECC 密钥对
    EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    if (!ec_key) {
        std::cerr << "Error: Failed to create ECC key pair." << std::endl;
        return 1;
    }

    // 生成 ECC 密钥对
    if (!EC_KEY_generate_key(ec_key)) {
        std::cerr << "Error: Failed to generate ECC key pair." << std::endl;
        EC_KEY_free(ec_key);
        return 1;
    }

    // 将密钥保存为 PEM 格式
    FILE *priv_key_file = fopen("private_key.pem", "wb");
    FILE *pub_key_file = fopen("public_key.pem", "wb");
    PEM_write_ECPrivateKey(priv_key_file, ec_key, NULL, NULL, 0, NULL, NULL);
    PEM_write_EC_PUBKEY(pub_key_file, ec_key);

    std::cout << "ECC key pair generated and saved as private_key.pem and public_key.pem." << std::endl;

    // 释放内存并清理 OpenSSL 库
    EC_KEY_free(ec_key);
    fclose(priv_key_file);
    fclose(pub_key_file);
    EVP_cleanup();

    return 0;
}
